package com.shamar.blog.web.backend;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shamar.blog.dto.BlogAdminExecution;
import com.shamar.blog.dto.BlogUserExecution;
import com.shamar.blog.entity.BlogAdmin;
import com.shamar.blog.entity.BlogUser;
import com.shamar.blog.enums.BlogUserStateEnum;
import com.shamar.blog.service.BlogAdminService;
import com.shamar.blog.service.BlogUserService;
import com.shamar.blog.util.CodeUtil;
import com.shamar.blog.util.HttpServletRequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * @author shamarfang
 * @date 2020-08-02 00:12
 * @desc 管理员后台controller
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private BlogAdminService blogAdminService;
    @Autowired
    private BlogUserService blogUserService;


    /**
     * 后台首页页面
     * @param request
     * @return
     */
    @GetMapping(value = "/index")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request){
        //直接返回jsp页面
        return new ModelAndView("backend/index");
    }
    /**
     * 获取所有用户数据
     * @param request
     * @return
     */
    @GetMapping(value = "/listuser")
    @ResponseBody
    public ModelAndView listUser(HttpServletRequest request) {
        //定义返回值
        ModelAndView  model  =  new ModelAndView("backend/user_list");
        try {
            BlogUser blogUserCondition = new BlogUser();
            BlogUserExecution blogUserExecution = blogUserService.getBlogUserList(blogUserCondition,0,100);
            model.addObject("blogUserList",blogUserExecution.getBlogUserList());
        } catch (Exception e) {
            logger.error("获取用户数据失败，错误：{}", e.getMessage());
        }
        return model;
    }

    /**
     * 注册页面
     * @param request
     * @return
     */
    @GetMapping(value = "/register")
    @ResponseBody
    public ModelAndView register(HttpServletRequest request){
        //定义返回值
        return new ModelAndView("backend/user_register");
    }

    /**
     * 处理注册的函数
     * @param request
     * @return
     */
    @PostMapping(value = "/doregister")
    @ResponseBody
    public Map<String, Object> doRegister(HttpServletRequest request){
        //定义返回值
        Map<String, Object> modelMap = new HashMap<>();
        BlogUser blogUser = null;
        if (!CodeUtil.checkVerifyCode(request)) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "验证码输入错误");
            return modelMap;
        }
        ObjectMapper mapper = new ObjectMapper();
        String blogUserStr = HttpServletRequestUtil.getString(request, "BlogUserStr");
        MultipartHttpServletRequest multipartRequest = null;
        CommonsMultipartFile blogUserImg = null;
        //从会话上下文中获取上传文件相关的内容
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //如果有上传的文件流
        if (multipartResolver.isMultipart(request)) {
            multipartRequest = (MultipartHttpServletRequest) request;
            blogUserImg = (CommonsMultipartFile) multipartRequest
                    .getFile("userimg");
        }
//		else {
//			modelMap.put("success", false);
//			modelMap.put("errMsg", "上传图片不能为空");
//			return modelMap;
//		}
        //以上接收前端传递过来的信息,下面使用jackson json databind转换为shop实体类
        try {
            //获取前端传来的数据
            blogUser = mapper.readValue(blogUserStr, BlogUser.class);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.toString());
            return modelMap;
        }
        //2. 新增用户
        if (Objects.nonNull(blogUser)) {
            try {
//				File userImgFile = new File(FileUtil.getImgBasePath() + FileUtil.getRandomFileName());
//				try {
//					userImgFile.createNewFile();
//				} catch (IOException e) {
//					modelMap.put("success", false);
//					modelMap.put("errMsg", e.toString());
//					return modelMap;
//				}
//				try {
//					inputStreamToFile(blogUserImg.getInputStream(),userImgFile);
//				} catch (IOException e) {
//					modelMap.put("success", false);
//					modelMap.put("errMsg", e.toString());
//					return modelMap;
//				}
                BlogUserExecution bue;
                try {
                    //若上传了图片则将图片传入Service层
                    if(Objects.nonNull(blogUserImg)){
                        bue = blogUserService.addBlogUser(blogUser, blogUserImg.getInputStream(), blogUserImg.getOriginalFilename());
                    }
                    //若为传入图片则文件传输流为null
                    else {
                        bue = blogUserService.addBlogUser(blogUser, null, null);
                    }
                    if (bue.getState() == BlogUserStateEnum.NORMAL.getState()) {
                        modelMap.put("success", true);
    				// 若shop创建成功，则加入session中，作为权限使用
                    } else {
                        modelMap.put("success", false);
                        modelMap.put("errMsg", bue.getStateInfo());
                    }
                } catch (Exception e) {
                    modelMap.put("success", false);
//					modelMap.put("errMsg", e.getMessage());
                    modelMap.put("errMsg", "出错");
                    return modelMap;
                }
            } catch (RuntimeException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", "RuntimeException");
                return modelMap;
            }
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "请输入用户信息");
        }
        return modelMap;
    }
    /**
     * 管理员login处理逻辑函数
     * @param request
     * @return
     */
    @PostMapping(value = "/doadminlogin")
    @ResponseBody
    public Map<String,Object> doAdminLogin(HttpServletRequest request){
        //定义返回值
        Map<String,Object> modelMap = new HashMap<>();
        if (!CodeUtil.checkVerifyCode(request)) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "验证码输入错误");
            return modelMap;
        }
        ObjectMapper mapper = new ObjectMapper();
        BlogAdmin blogAdmin;
        String adminStr = HttpServletRequestUtil.getString(request, "adminStr");
        //以上接收前端传递过来的信息,下面使用jackson json databind转换为BlogAdmin实体类
        try {
            blogAdmin = mapper.readValue(adminStr, BlogAdmin.class);
        }catch (Exception e){
            modelMap.put("success", false);
            modelMap.put("errMsg", e.toString());
            return modelMap;
        }
        if (Objects.nonNull(blogAdmin)){
            //若前端传来的blogAdmin不为空,和数据库比对是否有该用户
            //获得登录管理员的信息
            BlogAdminExecution be = blogAdminService.getBlogAdminByCondition(blogAdmin,0,100);
            //若数据库中存在符合条件的记录
            if (Objects.nonNull(be.getBlogAdmin())){
            BlogAdmin currentBlogAdmin = be.getBlogAdmin();
            request.getSession().setAttribute("currentBlogAdmin", currentBlogAdmin);
            modelMap.put("success", true);
            modelMap.put("currentBlogAdmin",currentBlogAdmin);
            return modelMap;
            }
            modelMap.put("success", false);
            modelMap.put("errMsg", "用户名或密码错误");
            return modelMap;
        }
        modelMap.put("success", false);
        modelMap.put("errMsg", "管理员为空");
        return modelMap;
    }
    /**
     * 管理员login页面
     * @param request
     * @return
     */
    @GetMapping(value = "/adminlogin")
    @ResponseBody
    public ModelAndView login(HttpServletRequest request){
        //定义返回值
        return new ModelAndView("backend/admin_login");
    }

    @PostMapping(value = "/testlogin")
    @ResponseBody
    public Map<String,Object> testLogin(HttpServletRequest request){
        //定义返回值
        Map<String,Object> modelMap = new HashMap<>();
        Object currentBlogAdminObj = request.getSession().getAttribute("currentBlogAdmin");
//        若session中没有数据,则未登录
        if (currentBlogAdminObj == null){
            modelMap.put("success",false);
            modelMap.put("errMsg","未登录");
        }
        else{
            BlogAdmin blogAdmin = (BlogAdmin) currentBlogAdminObj;
            if (blogAdmin.getId()!= 0){
                modelMap.put("success",true);
                modelMap.put("errMsg","已登录");
            }
        }
        return modelMap;
    }

    /**
     * 管理员登出功能
     * @param request
     * @return
     */
    @PostMapping(value = "/doadminlogout")
    @ResponseBody
    public Map<String,Object> doAdminLogout(HttpServletRequest request){
        //定义返回值
        Map<String,Object> modelMap = new HashMap<>();
        Object currentBlogAdminObj = request.getSession().getAttribute("currentBlogAdmin");
        if (Objects.nonNull(currentBlogAdminObj)){
            request.getSession().removeAttribute("currentBlogAdmin");
        }
        try {
            Object newCurrentBlogAdminObj = request.getSession().getAttribute("currentBlogAdmin");
            modelMap.put("success", Objects.isNull(newCurrentBlogAdminObj));
        }catch (Exception e){
            logger.error("用户登出失败，错误信息：{}", e.getMessage());
        }
//        若session中没有数据,则未登录
        return modelMap;
    }
    /**
     * 管理员个人页面
     * @param request
     * @return
     */
    @GetMapping(value = "/adminprofile")
    @ResponseBody
    public ModelAndView adminProfile(HttpServletRequest request){
        //定义返回值
        return new ModelAndView("backend/admin_profile");
    }


}
